package com.myelasticsearch.utils;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import java.net.InetAddress;

/**
 * elasticsearch工具类
 * @author zhouyong
 */
public class ESUtils {
	// 集群名称：ES-HOME//config/elasticsearch.yml文件中cluster.name
    private static String clusterName = "my-application";
    private static String[] esHosts = {"bd1", "bd2","bd3","bd4"};
	private static int esPort = 9300;

    // 设置client.transport.sniff为true来使客户端去嗅探整个集群的状态，把集群中其它机器的ip地址加到客户端中，
    static Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName).put("client.transport.sniff", true).build();
    private static TransportClient createClient(){
        TransportClient client = null;
    	try {
            //这是第一个优化点 以前加了一个点，现在加上所有点
            client = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.22.0.21"), esPort))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.22.0.22"), esPort))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.22.0.23"), esPort))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.22.0.24"), esPort));
        } catch (Exception e) {
            e.printStackTrace();
        }
    	return client;
    }

    // 取得实例
    public static TransportClient getTransportClient() {
        return createClient();
    }
}